{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 20. 有效的括号"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "给定一个只包括 '('，')'，'{'，'}'，'['，']' 的字符串，判断字符串是否有效。\n",
    "\n",
    "有效字符串需满足：\n",
    "\n",
    "左括号必须用相同类型的右括号闭合。\n",
    "左括号必须以正确的顺序闭合。\n",
    "注意空字符串可被认为是有效字符串。\n",
    "\n",
    "示例 1:\n",
    "\n",
    "输入: \"()\"\n",
    "输出: true\n",
    "示例 2:\n",
    "\n",
    "输入: \"()[]{}\"\n",
    "输出: true\n",
    "示例 3:\n",
    "\n",
    "输入: \"(]\"\n",
    "输出: false\n",
    "示例 4:\n",
    "\n",
    "输入: \"([)]\"\n",
    "输出: false\n",
    "示例 5:\n",
    "\n",
    "输入: \"{[]}\"\n",
    "输出: true\n",
    "\n",
    "来源：力扣（LeetCode）\n",
    "链接：https://leetcode-cn.com/problems/valid-parentheses"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "pycharm": {
     "is_executing": false,
     "name": "#%%\n"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n"
     ]
    }
   ],
   "source": [
    "class Solution(object):\n",
    "    def isValid(self, s):\n",
    "        \"\"\"\n",
    "        :type s: str\n",
    "        :rtype: bool\n",
    "        \"\"\"\n",
    "        dic = {'{': '}',  '[': ']', '(': ')', '?': '?'}\n",
    "        stack = ['?']\n",
    "        for c in s:\n",
    "            if c in dic: \n",
    "                stack.append(c)\n",
    "            elif dic[stack.pop()] != c: \n",
    "                return False \n",
    "        return len(stack) == 1\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    Sol = Solution()\n",
    "    end = Sol.isValid(\"()[]{}\")\n",
    "    print(end)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "pycharm": {
     "is_executing": false,
     "name": "#%%\n"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n"
     ]
    }
   ],
   "source": [
    "class Solution(object):\n",
    "    def isValid(self, s):\n",
    "        \"\"\"\n",
    "        :type s: str\n",
    "        :rtype: bool\n",
    "        \"\"\"\n",
    "        if not s:\n",
    "            return True\n",
    "        # 用栈保存 (，[，{\n",
    "        stack = []\n",
    "        # map中保存的是 ):(, ]:[,}:{\n",
    "        # 当遍历到 )时候就会去map中找对应的value，也就是(\n",
    "        # 再用这个value和stack弹出的元素比较，如果相等则匹配上，不等则返回false\n",
    "        # 这里也可以用数组来存，我为了简单就用map表示了\n",
    "        d = {\")\":\"(\", \"]\":\"[\",\"}\":\"{\"}\n",
    "        # 开始遍历字符串\n",
    "        for i in s:\n",
    "            # 如果map中不包含 (,[,{，就将这个字符放入栈中\n",
    "            if i not in d:\n",
    "                stack.append(i)\n",
    "            else:\n",
    "                # 如果遍历的字符不再map中，也就是说这个字符是),],}，那么就要跟栈中的元素比较\n",
    "                # 首先要判断栈是否为空，如果输入的字符是 )() ，那么当遍历到第一个)时，栈为空\n",
    "                if not stack:\n",
    "                    return False\n",
    "                # 取出栈顶的元素\t\n",
    "                tmp = stack.pop()\n",
    "                # 假设当前遍历到的元素是 ]，那么从map中取到的value就是 [\n",
    "                # 如果栈顶的元素是 (，则不匹配返回false，否则继续\n",
    "                if d[i]!=tmp:\n",
    "                    return False\n",
    "\t\t# 返回的时候还要判断栈是否为空\n",
    "        # 如果输入的字符串是 (((，那么最后栈就不为空\n",
    "        \n",
    "        return True if not stack else False\n",
    "    \n",
    "if __name__ == '__main__':\n",
    "    Sol = Solution()\n",
    "    end = Sol.isValid(\"()[]{}\")\n",
    "    print(end)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.5"
  },
  "pycharm": {
   "stem_cell": {
    "cell_type": "raw",
    "source": [],
    "metadata": {
     "collapsed": false
    }
   }
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}